<template>
  <div class="work-container">
    <van-tabs
      v-model="activeName"
      color="#1989fa"
      line-width="24px"
      line-height="4px"
      sticky
      animated
      @click="handleClick"
    >
      <van-tab
        title="计件报工"
        name="first"
      >
        <div
          v-if="activeName==='first'"
          class="job-list"
        >
          <van-list
            v-model="loading"
            :finished="finished"
            @load="load"
          >
            <div
              v-for="(item, index) in list"
              :key="index"
              class="job-item"
            >
              <div class="job-header">
                <div class="tit"><b>业务类型：</b>计件报工</div>
                <div class="pull-r">
                  <van-icon
                    v-hasPermi="['sl:rwork:edit']"
                    name="edit"
                    size="20"
                    color="#1989fa"
                    @click="gotoCreate(item.rworkId)"
                  />
                  <van-icon
                    v-hasPermi="['sl:rwork:remove']"
                    name="delete-o"
                    size="20"
                    color="#ff4949"
                    @click="handleDelete(item.rworkId)"
                  />
                </div>
              </div>
              <div class="job-body">
                <dl>
                  <dt>模块：</dt>
                  <dd>{{item.slModule.moduleName}}</dd>
                </dl>
                <dl>
                  <dt>车间：</dt>
                  <dd>{{item.slWorkshop.workshopName}}</dd>
                </dl>
                <dl>
                  <dt>报工人：</dt>
                  <dd>{{item.rworkNick}}</dd>
                </dl>
                <!-- <dl>
                  <dt>大工序：</dt>
                  <dd>{{item.slGprocess.gprocessName}}</dd>
                </dl> -->
                <dl>
                  <dt>小工序：</dt>
                  <dd>{{item.slProcess.processName}}</dd>
                </dl>
                <dl>
                  <dt>开始时间：</dt>
                  <dd>{{item.rworkStart}}</dd>
                </dl>
                <dl>
                  <dt>结束时间：</dt>
                  <dd>{{item.rworkEnd}}</dd>
                </dl>
              </div>
            </div>
            <van-empty
              v-if="!list.length"
              description="暂无报工数据"
            />
          </van-list>
        </div>
      </van-tab>
      <van-tab
        title="零工报工"
        name="second"
      >
        <div
          v-if="activeName==='second'"
          class="job-list"
        >
          <van-list
            v-model="loading"
            :finished="finished"
            @load="load"
          >
            <div
              v-for="(item, index) in list"
              :key="index"
              class="job-item"
            >
              <div class="job-header">
                <div class="tit"><b>业务类型：</b>零工报工</div>
                <div class="pull-r">
                  <van-icon
                    v-hasPermi="['sl:oddjob:edit']"
                    name="edit"
                    size="20"
                    color="#1989fa"
                    @click="gotoCreate(item.oddjobId)"
                  />
                  <van-icon
                    v-hasPermi="['sl:oddjob:remove']"
                    name="delete-o"
                    size="20"
                    color="#ff4949"
                    @click="handleDelete(item.oddjobId)"
                  />
                </div>
              </div>
              <div class="job-body">
                <dl>
                  <dt>出工方式：</dt>
                  <dd>{{item.wm.wmName}}</dd>
                </dl>
                <dl>
                  <dt>开始时间：</dt>
                  <dd>{{item.oddjobStart}}</dd>
                </dl>
                <dl>
                  <dt>结束时间：</dt>
                  <dd>{{item.oddjobEnd}}</dd>
                </dl>
              </div>
            </div>
            <van-empty
              v-if="!list.length"
              description="暂无报工数据"
            />
          </van-list>
        </div>
      </van-tab>
    </van-tabs>

    <div class="fixed-bar">
      <van-button
        v-hasPermi="['sl:rwork:add', 'sl:oddjob:add']"
        type="primary"
        round
        @click="gotoCreate()"
      >新增报工</van-button>
      <van-button
        :disabled="!list.length"
        type="info"
        round
        @click="showUserList"
      >提交当日报工</van-button>
    </div>

    <van-popup
      v-model="rworkUserShow"
      round
      position="bottom"
    >
      <van-nav-bar title="计件员工出勤" />
      <van-form @submit="submitRworkDate">
        <div style="height: 60vh; overflow: auto;">
          <van-field
            v-for="(item,index) in attendanceList"
            :key="index"
            :label="item.nickName"
            v-model="item.attendanceDay"
            type="number"
            :name="item.nickName"
            placeholder="出勤天数"
            :rules="[
            { required: true, message: '请填写出勤天数（0-2）' },
            { pattern: /^0(\.\d+)?$|^1(\.\d+)?$|^2(\.\d+)?$/, message: '出勤天数值为（0-2）' }
            ]"
          />
        </div>
        <div class="btn-box">
          <van-button
            round
            block
            type="default"
            @click="rworkUserShow=false"
          >取消</van-button>
          <van-button
            :loading="searchLoading"
            round
            block
            type="info"
            native-type="submit"
          >提交</van-button>
        </div>
      </van-form>
    </van-popup>

    <van-popup
      v-model="oddjobUserShow"
      round
      position="bottom"
    >
      <van-nav-bar title="零工员工出勤" />
      <van-form @submit="submitOddjobDate">
        <div style="height: 60vh; overflow: auto;">
          <van-field
            v-for="(item,index) in oddjobAttendanceList"
            :key="index"
            :label="item.nickName"
            v-model="item.attendanceDay"
            type="number"
            :name="item.nickName"
            placeholder="出勤天数"
            :rules="[{ required: true, message: '请填写出勤天数（0-2）' }]"
          />
        </div>
        <div class="btn-box">
          <van-button
            round
            block
            type="default"
            @click="oddjobUserShow=false"
          >取消</van-button>
          <van-button
            :loading="searchLoading"
            round
            block
            type="info"
            native-type="submit"
          >提交</van-button>
        </div>
      </van-form>
    </van-popup>
  </div>
</template>

<script>
import { Notify } from 'vant';
import { Dialog } from 'vant';

import { listNoSubmitRwork, delRwork, submitDateRworks } from "@/api/sl/rwork";
import { listNoSubmitOddjob, delOddjob, submitDateOddjobs } from "@/api/sl/oddjob";
import { allRworkMember, allRworkMemberByRworkId } from "@/api/sl/rmember.js";
import { allOddjobMember } from "@/api/sl/omember.js";

export default {
  name: "h5Job",
  components: {
    [Notify.Component.name]: Notify.Component,
    [Dialog.Component.name]: Dialog.Component,
  },
  data() {
    return {
      activeName: 'first',
      // 查询参数
      queryParams01: {
        pageNum: 1,
        pageSize: 10,
      },
      // 查询参数
      queryParams02: {
        pageNum: 1,
        pageSize: 10,
      },
      list: [],
      total: 0,
      finished: false,
      loading: false,
      searchLoading: false,
      rworkUserShow: false,
      oddjobUserShow: false,
      //所有参与人
      attendanceList: [],
      oddjobAttendanceList: []
    }
  },
  computed: {
  },
  created() {
    //获取当前报工人信息
    // this.getRworkUserBase(this.$store.state.user.name);
    this.load();
  },
  methods: {
    handleClick() {
      this.list = [];
      this.queryParams01.pageNum = 1;
      this.queryParams02.pageNum = 1;
      this.total = 0;
      this.finished = false;
      this.load();
    },
    load() {
      console.log(this.activeName);
      this.loading = true
      if (this.activeName === 'first') {
        this.getRworkList();
      } else {
        this.getOddjobList();
      }
    },
    /** 查询报工单列表 */
    getRworkList() {
      this.loading = true;
      if (!this.finished) {
        listNoSubmitRwork(this.queryParams01).then(response => {
          if (response.code === 200) {
            this.list = [...this.list, ...response.rows];
            this.total = response.total;
            //处理出勤人
            this.getAllRworkMember();
            this.loading = false;
            if (this.queryParams01.pageNum * this.queryParams01.pageSize < this.total) {
              this.finished = false;
              this.queryParams01.pageNum += 1;
            } else {
              this.finished = true;
            }
          } else {
            Notify({ type: 'danger', message: '出错了' });
          }
        })
      }

    },
    getOddjobList() {
      this.loading = true;
      if (!this.finished) {
        listNoSubmitOddjob(this.queryParams02).then(response => {
          if (response.code === 200) {
            this.list = [...this.list, ...response.rows];
            this.total = response.total;
            //处理出勤人
            this.getAllOddjobMember();
            this.loading = false;
            if (this.queryParams01.pageNum * this.queryParams02.pageSize < this.total) {
              this.finished = false;
              this.queryParams02.pageNum += 1;
            } else {
              this.finished = true;
            }
          } else {
            Notify({ type: 'danger', message: '出错了' });
          }
        });
      }
    },
    gotoCreate(id) {
      if (this.activeName === 'first') {
        if (id) {
          this.$router.push({
            path: '/h5/rwork-edit', query: {
              rworkId: id
            }
          })
        } else {
          this.$router.push({ path: '/h5/rwork-edit' })
        }
      } else {
        if (id) {
          this.$router.push({
            path: '/h5/oddjob-edit', query: {
              oddjobId: id
            }
          })
        } else {
          this.$router.push({ path: '/h5/oddjob-edit' })
        }
      }

    },
    handleDelete(id) {
      Dialog.confirm({
        title: '提示',
        message: '是否确认删除报工单编号为"' + id + '"的数据项？',
      }).then(() => {
        // on confirm
        let obj;
        if (this.activeName === 'first') {
          obj = delRwork(id);
        } else {
          obj = delOddjob(id);
        }
        obj.then(() => {
          this.handleClick();
          Notify({ type: 'success', message: '删除成功' });
        });
      }).catch(() => {
        // on cancel
      });
    },
    //获取所有出勤人
    getAllRworkMember() {
      allRworkMember(this.queryParams01).then(response => {
        console.log(response.data)
        this.attendanceList = response.data.map(item => ({
          "userName": item.rmemberUser,
          "nickName": item.rmemberNick,
          "attendanceDay": 1
        }))
      });
    },
    //获取所有出勤人
    getAllOddjobMember() {
      allOddjobMember(this.queryParams02).then(response => {
        console.log(response.data)
        this.oddjobAttendanceList = response.data.map(item => ({
          "userName": item.omemberUser,
          "nickName": item.omemberNick,
          "attendanceDay": 1
        }))
        //this.attendanceList = response.data;
      });
    },
    showUserList() {
      if (this.activeName === 'first') {
        this.rworkUserShow = true;
      } else {
        this.oddjobUserShow = true;
      }
    },
    //当日报工单提交
    submitRworkDate(values) {
      console.log('submit');
      let valid = true;
      if (this.list.length == 0) {
        return;
      }
      //校验所有时长不能为空
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].rworkActual == null || this.list[i].rworkActual == "") {
          Notify({ type: 'danger', message: "请检查第" + (i + 1) + "条的实际生产" });
          valid = false;
          break;
        }
      }
      //校验所有人工勤不能为空
      for (let i = 0; i < this.attendanceList.length; i++) {
        if (this.attendanceList[i].attendanceDay == null || this.attendanceList[i].attendanceDay == "") {
          Notify({ type: 'danger', message: "参与人员" + this.attendanceList[i].nickName + "的出勤天数不能为空。" });
          valid = false;
          break;
        }
      }
      //校验所有小时工操作人的时长是否填写
      for (let i = 0; i < this.list.length; i++) {
        allRworkMemberByRworkId(this.list[i].rworkId).then(response => {
          let tmpMemberList = response.data;
          for (let n = 0; n < tmpMemberList.length; n++) {
            if (tmpMemberList[i].ssmId === 5) {
              if (tmpMemberList[i].rmemberDuration == null || tmpMemberList[i].rmemberDuration === "") {
                Notify({ type: 'danger', message: "第" + (i + 1) + "条报工项的操作人" + tmpMemberList[i].rmemberNick + "出勤时长不能为空。" });
                valid = false;
                break;
              }
            }
          }
        });
      }
      //提交整张报工单
      if (valid) {
        let tmpData = {};
        tmpData.rworks = this.list;
        tmpData.attendances = this.attendanceList;
        this.searchLoading = true;
        submitDateRworks(tmpData).then(response => {
          Notify({ type: 'success', message: "提交成功" });
          this.handleClick();
          this.searchLoading = false;
          this.rworkUserShow = false;
        });
      }
    },
    //当日零工报工单提交
    submitOddjobDate() {
      let valid = true;
      if (this.list.length == 0) {
        return;
      }
      //校验所有时长不能为空
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].oddjobDuration == null || this.list[i].oddjobDuration == "") {
          Notify({ type: 'danger', message: "请检查第" + (i + 1) + "条的工作时长" });
          valid = false;
          break;
        }
      }
      //校验所有人工勤不能为空
      for (let i = 0; i < this.oddjobAttendanceList.length; i++) {
        if (this.oddjobAttendanceList[i].attendanceDay == null || this.oddjobAttendanceList[i].attendanceDay == "") {
          Notify({ type: 'danger', message: "参与人员" + this.oddjobAttendanceList[i].nickName + "的出勤天数不能为空。" });
          valid = false;
          break;
        }
      }
      //提交整张报工单
      if (valid) {
        let tmpData = {};
        tmpData.oddjobs = this.list;
        tmpData.attendances = this.oddjobAttendanceList;
        console.log(tmpData)
        this.searchLoading = true;
        submitDateOddjobs(tmpData).then(response => {
          Notify({ type: 'success', message: "提交成功" });
          this.handleClick();
          this.searchLoading = false;
          this.oddjobUserShow = false;
        });

      }

    }
  }
};
</script>

<style lang="scss" scoped>
.job-list {
  padding: 15px 15px 80px;
  .job-item {
    padding: 15px;
    border-radius: 5px;
    background-color: #fff;
    & + .job-item {
      margin-top: 15px;
    }
    .job-header {
      display: flex;
      margin-bottom: 10px;
      font-size: 16px;
      .tit {
        flex: 1;
      }
      .pull-r {
        i + i {
          margin-left: 50px;
        }
      }
    }
    .job-body {
      padding: 10px;
      border-radius: 5px;
      background-color: #f3f5f7;
      dl {
        display: flex;
        margin: 0;
        font-size: 14px;
        & + dl {
          margin-top: 2px;
        }
        dt {
          width: 80px;
          text-align: justify;
          color: #999;
        }
        dd {
          margin-left: 0;
          flex: 1;
          color: #333;
        }
      }
    }
  }
}
.fixed-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: #fff;
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 0 10px 5px rgba(51, 51, 51, 0.04);
  button {
    width: 48%;
  }
}
.btn-box {
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  button {
    width: 48%;
  }
}
@media (max-width: 550px) {
}
</style>
